import { defineStore } from 'pinia'
import { 
    getBlogList, 
    getBlogDetail, 
    submitLike, 
    submitComment,
    getSubComments,
    getUserBlogs,
    deleteBlog,
    createBlog,
    editBlog,
    getLikedBlogs,
    deleteLikeBlog
} from '../api/blog'
import { message } from 'ant-design-vue'

export const useBlogStore = defineStore('blog', {
  state: () => ({
    currentBlog: null,
    loading: false,
    error: null,
    total: 0,
    likedBlogs: [], // 存储已点赞的文章ID
    cachedBlogs: {}, // 缓存已获取的博客数据
    cacheTimestamps: {} // 缓存时间戳
  }),
  actions: {
    async fetchBlogList(params = { page: 1, pageSize: 10 }) {
      this.loading = true
      try {
        const cacheKey = JSON.stringify(params)
        // 检查缓存是否有效(5分钟内)
        if (this.cacheTimestamps[cacheKey] && 
            Date.now() - this.cacheTimestamps[cacheKey] < 5 * 60 * 1000) {
          return {
            blogs: Object.values(this.cachedBlogs).filter(b => 
              this.cachedBlogs[b.id] && b.id
            ),
            total: this.total
          }
        }
        
        const result = await getBlogList(params)
        // 缓存获取到的博客数据并确保有author对象
        result.blogs.forEach(blog => {
          this.cachedBlogs[blog.id] = {
            ...blog,
            author: blog.author 
          }
        })
        this.total = result.total
        this.cacheTimestamps[cacheKey] = Date.now()
        return result
      } catch (error) {
        this.error = error
        throw error
      } finally {
        this.loading = false
      }
    },
    async fetchBlogDetail(id,page = 1, pagesize = 10) {
      this.loading = true
      try {
        // 详情页不使用缓存，直接获取最新数据
        const blog = await getBlogDetail(id,page,pagesize)
        if (blog) {
          this.currentBlog = { 
            ...blog
          }
        }
        return this.currentBlog
      } catch (error) {
        this.error = error
        throw error
      } finally {
        this.loading = false
      }
    },
    async likeBlog(blogId) {
      if (this.likedBlogs.includes(blogId)) {
         return false
      }
      try {
        await submitLike(blogId)
        if (this.currentBlog?.id === blogId) {
          this.currentBlog.likes += 1
        }
        this.likedBlogs.push(blogId)
        return true
      } catch (error) {
        throw error;
      }
    },
    async addComment(blogId, content, parentId = "") {
      try {
        const result = await submitComment(blogId, content, parentId)
        if (this.currentBlog?.id === blogId) {
          // 如果是回复评论，不要添加到顶层评论列表
          if (!parentId) {
            this.currentBlog.comments.unshift(result.comment)
          }
        }
        return result
      } catch (error) {
        this.$message.error("评论失败 ",error);
      }
    },
    async fetchSubComments(blogId, parentId, page, pageSize) {
      try {
        const result = await getSubComments(blogId, parentId, page, pageSize)
        return result
      } catch (error) {
        this.$message.error("评论失败 ",error);
      }
    },
    async getPublishedBlogs(email, page, pagesize) {
        // 获取用户已发布的博客文章
        try{
            const { blogs, total } = await getUserBlogs(email, true, page, pagesize);
            return { blogs, total }
        }catch(error) {
            throw error
        }
    },
    async getDraftBlogs(email, page, pagesize) {
        // 获取用户的草稿博客文章
        try{
            const { blogs, total } = await getUserBlogs(email, false, page, pagesize);
            return { blogs, total }
        }catch(error) {
            throw error
        }
    },
    async deleteBlog(blogId) {
        try{
            const result = await deleteBlog(blogId)
            return result
        }catch(error) {
            throw error
        }
    },
    async createBlog(blogId,title, content, published) {
        try{
            const result = await createBlog(blogId,title, content, published)
            return result
        }catch(error) {
            throw error
        }
    },
    async editBlog(blogId) {
        try{
            const result = await editBlog(blogId)
            return result
        }catch(error) {
            throw error
        }
    },
    async getLikedBlogs(email, page, pagesize) {
        try{
            const result = await getLikedBlogs(email, page, pagesize)
            return result
        }catch(error) {
            throw error
        }
    },
    async deleteLikeBlog(blogId) {
        try{
            const result = await deleteLikeBlog(blogId)
            return result
        }catch(error) {
            throw error
        }
    }
  },
  getters: {
    getBlogById: (state) => (id) => {
      return state.cachedBlogs[id]
    },
    isBlogLiked: (state) => (blogId) => {
      return state.likedBlogs.includes(blogId)
    }
  }
})
